package com.ygqh.baby.controller.admin;

import com.alibaba.fastjson.JSON;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.model.BaseEditRequest;
import com.ygqh.baby.po.AdminUser;
import com.ygqh.baby.shiro.utils.SessionUtil;
import com.ygqh.baby.utils.DateConvertUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


public class BaseController<Entity, PK> {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    // ** 错误消息 *//*
    protected static final Message ERROR_MESSAGE = Message.error("操作失败", null);
    // ** 成功消息 *//*
    protected static final Message SUCCESS_MESSAGE = Message.success("操作成功", null);
    protected static final BigDecimal ZERO = new BigDecimal("0.00");

    public AdminUser getSession() {
        return SessionUtil.getCurrentUser();

    }
    protected  <T extends BaseEditRequest> void initEdit(T t){
        t.setHandler(getSession().getTrueName());
        t.setUpdateTime(new Date());
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); // true:允许输入空值，false:不能为空值
    }

    protected String getRequestPostStr(HttpServletRequest request) {
        try {
            byte buffer[] = getRequestPostBytes(request);
            String charEncoding = request.getCharacterEncoding();
            if (charEncoding == null) {
                charEncoding = "UTF-8";
            }
            return new String(buffer, charEncoding);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    protected byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if (contentLength < 0) {
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength; ) {

            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Message execute(HttpServletRequest request, Exception ex) {
        String methodName = request.getRequestURI();

        Map<String, String[]> parameterMap = request.getParameterMap();
        String param = JSON.toJSONString(parameterMap);

        // TODO
        StringBuilder sb = new StringBuilder();
        sb.append("【methodName】=" + methodName).append(";【param】=" + param + "</br>")
                .append("【异常类型】:" + ex.getClass().getName() + "【" + ex.getMessage() + "】</br>");
        StackTraceElement[] st = ex.getStackTrace();
        for (StackTraceElement stackTraceElement : st) {
            String exclass = stackTraceElement.getClassName();
            String method = stackTraceElement.getMethodName();
            if (exclass.contains("com.ygqh.baby")) {
                sb.append(DateConvertUtils.formatDateTime(new Date()) + ":" + "[类:" + exclass + "]调用" + method + "时在第" + stackTraceElement.getLineNumber()
                        + "行代码处发生异常!");
            }
        }
        ex.printStackTrace();
        logger.error(sb.toString(),ex);
        return Message.error(ex.getClass().getName() + " " + ex.getMessage(), null);
    }

}
